package com.chenfan.process.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.chenfan.ccp.common.exception.ApiException;
import com.chenfan.process.common.exception.ProcessResultCode;
import com.chenfan.process.dto.ApprovalDTO;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author liuming
 * @date 2021/10/8
 */
public class ParseValueValidator {

    public static String parseValue(ApprovalDTO.CheckField checkField, String verifyField) {
        if (!StringUtils.isEmpty(verifyField)) {
            return validateAndGetValue(checkField, verifyField);
        }
        return null;
    }

    private static String validateAndGetValue(ApprovalDTO.CheckField checkField, String verifyField) {
        if (Objects.isNull(checkField)) {
            throw new ApiException(ProcessResultCode.REQUIRE_CHECK_FIELD);
        }
        JSONObject verify = JSONObject.parseObject(verifyField, JSONObject.class);
        JSONObject check = JSONObject.parseObject(checkField.getCheckFields(), JSONObject.class);
        if (StringUtils.isEmpty(check)) {
            throw new ApiException(ProcessResultCode.REQUIRE_CHECK_FIELD_NOT_CORRECT);
        }

        AtomicReference<String> value = new AtomicReference<>("");
        check.forEach((k, v) -> {
            String checkKey = verify.getString(k);
            if (Objects.nonNull(checkKey)) {
                value.set(String.valueOf(v));
            }
        });

        if (StringUtils.isEmpty(value)) {
            // 压根找不到这个要检查的Key.说明是Key配置错误或者其他问题
            throw new ApiException(ProcessResultCode.REQUIRE_CHECK_FIELD_NOT_CORRECT);
        }
        return value.get();
    }
}
